<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="权限名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      style="width: 100%; margin-top:10px;"
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="150" prop="id">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="权限编号" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.menuId }}
        </template>
      </el-table-column>
      <el-table-column label="权限名称" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.menuName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限路径" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.url }}
        </template>
      </el-table-column>
      <el-table-column label="父权限" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.menuPid }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row.menuId)">
            修改
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.menuId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="formRules" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px;">
        <el-form-item label="权限编号" prop="menuId" label-width="100px">
          <el-input v-model="temp.menuId" />
        </el-form-item>
        <el-form-item label="权限名称" prop="menuName" label-width="100px">
          <el-input v-model="temp.menuName" />
        </el-form-item>
        <el-form-item label="权限路径" prop="url" label-width="100px">
          <el-input v-model="temp.url" />
        </el-form-item>
        <el-form-item label="父权限" prop="method" label-width="100px">
          <el-input v-model="temp.menuPid" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getPowerList, getPower, addPower, updatePower, deletePower } from '@/api/power'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  data() {
    const validatePowerId = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('权限编号不能为空'))
      } else {
        callback()
      }
    }
    const validatePowerName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('权限名称不能为空'))
      } else {
        callback()
      }
    }
    const validateRePath = (rule, value, callback) => {
      if (this.dialogStatus === 'create' && value === '') {
        callback(new Error('权限路径不能为空'))
      } else {
        callback()
      }
    }
    const validateMethod = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请求类型不能为空'))
      } else {
        callback()
      }
    }
    return {
      formRules: {
        powerId: [{ required: true, trigger: 'blur', validator: validatePowerId }],
        powerName: [{ required: true, trigger: 'blur', validator: validatePowerName }],
        resourcePath: [{ required: true, trigger: 'blur', validator: validateRePath }],
        method: [{ required: true, trigger: 'blur', validator: validateMethod }]
      },
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        title: undefined
      },
      list: null,
      total: 0,
      listLoading: true,
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogStatus: '',
      dialogFormVisible: false,
      temp: {
        menuId: '',
        menuName: '',
        url: '',
        menuPid: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleFilter() {
      this.listQuery.pageNum = 1
      if (this.listQuery.title.length === 0) {
        this.listQuery.title = undefined
      }
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getPowerList(this.listQuery).then(response => {
        this.list = response.data.content
        this.total = response.data.totalSize
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userId: '',
        username: '',
        password: '',
        telephone: '',
        status: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addPower(this.temp).then(() => {
            this.list.push(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      getPower(row).then(response => {
        this.temp = Object.assign({}, response.data) // copy obj
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updatePower(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(id) {
      this.dialogdeleteVisible = true
      this.temp.id = id
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePower(this.temp.id).then(() => {
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1, this.temp)
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    }
  }
}
</script>
